$(function () {
    new AjaxUpload('#upload', {
        action: baseURL + "sys/upload/imgUpload",
        name: 'imgFile',
        autoSubmit:true,
        responseType:"json",
        onComplete : function(file, r){
            if(r.code == 0){
                alert("图片上传成功！！");
                $("#bingimg").attr('src',r.url);
                vm.btCustomerMessage.img = r.url;
            }else{
                alert(r.msg);
            }
        }
    });
});
//初始化表格
var creatjqg;
function creatjqGrid() {
    creatjqg= $("#jqGrid").jqGrid({
        url: baseURL + 'sys/btcustomermessage/list',
        datatype: "json",
        colModel: [
            { label: 'id', name: 'id', index: 'id', width: 50, key: true },
            { label: '标题', name: 'title', index: 'title', width: 80 },
            { label: '主图', name: 'img', index: 'img', width: 80 },
            { label: '摘要', name: 'summary', index: 'summary', width: 80 },
            { label: '创建时间', name: 'creattime', index: 'creattime', width: 80 },
            { label: '点击次数', name: 'clickcnt', index: 'clickcnt', width: 80 },
            { label: '详情', name: 'detail', index: 'detail', width: 80 }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        postData:{'typestr':vm.clickTreeNode.typestr},
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
}
//富文本
var editor;
//文本编辑器
function kedit(kedit) {
    editor = KindEditor.create(kedit, {
        width: '1400px',
        height: '600px',
        resizeMode: 0,
        allowPreviewEmoticons: false,
        allowImageUpload: true,//允许上传图片
        allowFileManager: true, //允许对上传图片进行管理
        uploadJson: baseURL+'sys/upload/imgUpload', //上传图片的java代码
        fileManagerJson: baseURL+'/upload/fileManager',
        afterUpload: function () {
            this.sync();
        }, //图片上传后，将上传内容同步到textarea中
        afterBlur: function () {
            this.sync();
        }, //失去焦点时，将上传内容同步到textarea中

        items: [
            'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'cut', 'copy', 'paste',
            'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
            'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
            'superscript', 'clearhtml', 'selectall', '|', 'fullscreen', '/',
            'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
            'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
            'table', 'hr', 'emoticons', 'baidumap','media'
        ]
    });
};
//ztree基本配置
var Category_ztree;
var CategoryZtree_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    check: {
        enable: false,
        nocheckInherit: true
    },
    callback: {
        onClick: zTreeOnClick
    }
};

function zTreeOnClick(event, treeId, treeNode, clickFlag) {
    if(vm==undefined){
        $("#showtable").hide();
        $("#unshowtable").hide();
        $("#addormod").hide();
        $("#unshowtable").show();
        $("#unshowtable>strong").html("请点击子分类查看课程！！")
    }else{
        vm.clickZtreeNode(treeNode);
    }
}

var vm = new Vue({
	el:'#rrapp',
	data:{
		title: null,
        clickTreeNode:{},
        categdata:{},
        q:{
            name:""
        },
        imgarr:[],
        btCustomerMessage: {}

	},
	methods: {
        deleteimg:function (img) {
            vm.imgarr.splice(vm.imgarr.indexOf(img),1);
            vm.btCustomerMessage.img=vm.imgarr.join(';');
        },
		query: function () {
			vm.reload();
		},
        //列表操作 b
		add: function(){
            $("#showtable").hide();
            $("#unshowtable").hide();
            $("#addormod").show();
            vm.imgarr=[];
            vm.btCustomerMessage = {img:""};
			vm.title = vm.clickTreeNode.name+"添加";
            var t;
            clearTimeout(t);
            KindEditor.remove('textarea[name="contentDetail"]');
            t = setTimeout(function (){
                kedit('textarea[name="contentDetail"]');
            }, 500);
		},
		update: function (event) {

			var id = getSelectedRow();
			if(id == null){
				return ;
			}
            $("#showtable").hide();
            $("#unshowtable").hide();
            $("#addormod").show();
            vm.title = "修改";
            
            vm.getInfo(id);
            $.get(baseURL + "sys/catagroyManager/getmaincatagroy", function(r){
                vm.maincatagroy = r.maincatagroy;
            });
		},
		saveOrUpdate: function (event) {
			var url = vm.btCustomerMessage.id == null ? "sys/btcustomermessage/save" : "sys/btcustomermessage/update";

            if (vm.btCustomerMessage.clickcnt == "" || vm.btCustomerMessage.clickcnt == null) {
                alert("请输入浏览次数");
                return;
            }
            var pattern = /^[0-9]*[1-9][0-9]*$/;
            if (!pattern.test(vm.btCustomerMessage.clickcnt)) {
                alert("请输入整数");
                return;
            }
            if(vm.btCustomerMessage.img==""){
                alert("请上传课程图片");
                return;
            }
            if(vm.btCustomerMessage.title==""){
                alert("请输入标题");
                return;
            }
            if(vm.btCustomerMessage.summary==""){
                alert("请输入摘要");
                return;
            }

            vm.btCustomerMessage.typestr = vm.clickTreeNode.typestr;
            vm.btCustomerMessage.detail = encodeURIComponent($("#activity_detail").val());
            vm.btCustomerMessage.creattime =$("#timeval").val();
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.btCustomerMessage),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},

		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/btnavbar/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "sys/btcustomerprobaseinfo/info/"+id, function(r){
                vm.btCustomerProBaseinfo = r.btCustomerProBaseinfo;
                if(vm.btCustomerProBaseinfo.imgs==null|| vm.btCustomerProBaseinfo.imgs==""){
                    vm.imgarr=null;
                    vm.btCustomerProBaseinfo.imgs=""
                }else{
                    vm.imgarr= vm.btCustomerProBaseinfo.imgs.split(";");
                }
                $.get(baseURL + "sys/btcustomerprodetail/info/"+vm.btCustomerProBaseinfo.id, function(r){
                    if(!r.hasOwnProperty("btCustomerProDetail")|| r.btCustomerProDetail==null){
                        r.btCustomerProDetail={};
                        r.btCustomerProDetail.proId="";
                        r.btCustomerProDetail.context="";
                    }
                    vm.btCustomerProDetail = r.btCustomerProDetail;
                    var t;
                    clearTimeout(t);
                    KindEditor.remove('textarea[name="contentDetail"]');
                    t = setTimeout(function (){
                        kedit('textarea[name="contentDetail"]');
                    }, 500);
                });
            });
		},
		reload: function () {
            vm.clickZtreeNode(vm.clickTreeNode);
		},
        //列表操作 e
		// ztree 操作
        clickZtreeNode: function (treeNode) {
            vm.clickTreeNode = treeNode;
            vm.showRightDiv(treeNode)
        },
        showRightDiv:function (treeNode) {
            vm.title = treeNode.name;
            $("#showtable").hide();
            $("#unshowtable").hide();
            $("#addormod").hide();
            if(treeNode.pid =="-1"){
                $("#unshowtable").show();
                $("#unshowtable>strong").html("请点击子分类查看课程！！")

            }else{
                $("#showtable").show();
                vm.productlist();
            }
        },
        productlist:function () {
            if(creatjqg == null){
                creatjqGrid();
            }else{
                var page = $("#jqGrid").jqGrid('getGridParam','page');
                $("#jqGrid").jqGrid('setGridParam',{
                    postData:{'typestr':vm.clickTreeNode.typestr},
                    page:page
                }).trigger("reloadGrid");
            }
        },
        getZTreeDateAndShow: function () {
                categroyztree =[
                    {'id':0,'pid':-1,'name':"信息管理",'typestr':''},
                    {'id':1,'pid':0,'name':"常见问题",'typestr':'cjwt'},
                    {'id':2,'pid':0,'name':"游学游记",'typestr':'yxyj'},
                    {'id':3,'pid':0,'name':"营地风采",'typestr':'ydfc'},
                    {'id':4,'pid':0,'name':"精彩瞬间",'typestr':'jcxj'},
                    {'id':5,'pid':0,'name':"预约咨询",'typestr':'yyzx'}
                ];
                Category_ztree = $.fn.zTree.init($("#CategoryZtree"), CategoryZtree_setting,categroyztree);
                //展开所有节点
                Category_ztree.expandAll(true);
                //调用默认展开第一个结点
                var nodes = Category_ztree.getNodes();
                var childNodes = Category_ztree.transformToArray(nodes[0]);
                Category_ztree.checkNode(childNodes[0], true, true);
                Category_ztree.selectNode(childNodes[0]); //选中第一个父节点下面第一个子节点
                Category_ztree.setting.callback.onClick(null, Category_ztree.setting.treeId, childNodes[0]);//点击第一个父节点下面第一个子节点
        }
        // ztree 操作e
	},
    mounted: function () {
        this.getZTreeDateAndShow();
    }
});